﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Contract;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SocketMessaging;
using TcpServer.Tool;
using Tool;

namespace TcpServer.SocketCommandImpl
{
    class NoticeFriendOnline : AbstractSocketCommand, ISocketCommand
    {
        public NoticeFriendOnline(ConcurrentDictionary<int, Connection> connectionMap, ConcurrentDictionary<int, Packet> dic)
           : base(connectionMap, dic)
        {

        }
        public void CallCommand(ReceiveData<object> receiveData, Connection connection = null)
        {
            JObject obj = receiveData.data as JObject;

            Packet packet = obj.ToObject<Packet>();

            List<Packet> list = new List<Packet>();

            packet.fd = connection.Id;

            dic.TryAdd(connection.Id, packet);

            foreach (KeyValuePair<int, Packet> pair in dic)
            {
                // 过滤自己
                if (pair.Key == connection.Id)
                {
                    pair.Value.userName = packet.userName;
                    continue;
                }

                list.Add(pair.Value);
            }


            
            ReceiveData<List<Packet>> sendeData = new ReceiveData<List<Packet>>(
                "online",
                1,
                list
            );

            connection.Send(JsonConvert.SerializeObject(sendeData));

            // 通知有人上线
            var otherClients = StaticProperties.server.Connections.Except(new[] {connection });

            Packet userInfo = new Packet();

            userInfo.userName = packet.userName;

            userInfo.fd = connection.Id;

            ReceiveData<Packet> notice = new ReceiveData<Packet>("notice_online", 1, userInfo);

            foreach (var client in otherClients)
            {
                if (client.Id == connection.Id)
                {
                    continue;
                }
                // 发送通知信息
                client.Send(JsonConvert.SerializeObject(notice));
            }

            Console.WriteLine($"#{connection.Id} has joined.");

        }
    }
}
